<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('menu.menuName')">
          {{ formSearch.menuName }}
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('menu.menuCode')">
          {{ formSearch.menuCode }}
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-menu-item-grid"
    row-key="randomKey"
    defaultSort="ascending"
    defaultSortBy="levelCode"
    :defaultExpandAll="false"
    :columns="state.columns"
    :buttons="state.buttons"
    pagination="{show:false}"
    lazy
    :data="state.initRows"
    :load="load"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
  >
    <template #button-primary="button">
      <el-button type="primary" :icon="Plus" @click="handleAdd">{{
        t("menu.newMenuItem")
      }}</el-button>
      <el-button @click="handleBack">
        <el-icon>
          <ico-svg icon="go-back-line"></ico-svg>
        </el-icon>
        &nbsp;{{ t("common.previousButton") }}
      </el-button>
    </template>

    <template #resourceId="slotProps">
      <el-tag size="small" v-if="slotProps.row.resourceId">
        {{ t("common.true") }}</el-tag
      >
      <el-tag size="small" type="info" v-if="!!!slotProps.row.resourceId">
        {{ t("common.false") }}</el-tag
      >
    </template>

    <template #visible="slotProps">
      <el-tag size="small" v-if="slotProps.row.visible == 1">
        {{ t("common.true") }}</el-tag
      >
      <el-tag size="small" type="info" v-if="slotProps.row.visible == 0">
        {{ t("common.false") }}</el-tag
      >
    </template>

    <template #image="slotProps">
      <el-image
        style="width: 24px; height: 24px"
        :src="slotProps.row.icon"
        fit="cover"
      ></el-image>
    </template>

    <template #operate="slotProps">
      <el-link type="primary" @click="handleEdit(slotProps.row)">
        {{ t("common.editButton") }}</el-link
      >
      &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row)"
        >{{ t("common.deleteButton") }}
      </el-link>
    </template>
  </data-grid>

  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import { Plus } from "@element-plus/icons-vue";
import { onBeforeMount } from "vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../../utils/utils";
import apiMenu from "../../api/menu";
import { useRouter } from "vue-router";
import MenuItemTreeNode from "./tree-node";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const router = useRouter();
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();

// 查询区域表单数据
const formSearch = reactive({
  menuId: "",
  menuCode: "",
  menuName: "",
});

const state = reactive({
  // 懒加载第一层初始化数据
  initRows: [],
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: () => t("menu.menuItemCnName"),
      field: "menuItemCnName",
      resizable: true,
    },
    {
      title: () => t("menu.menuItemEnName"),
      field: "menuItemEnName",
      resizable: true,
    },
    {
      title: () => t("menu.levelCode"),
      field: "levelCode",
      resizable: true,
      width: 150,
    },
    {
      title: () => t("menu.isResource"),
      field: "resourceId",
      width: 100,
      tdSlot: "resourceId",
    },
    {
      title: () => t("menu.isVisible"),
      field: "visible",
      width: 100,
      tdSlot: "visible",
    },
    {
      title: () => t("menu.icon"),
      field: "icon",
      width: 150,
    },
    {
      title: () => t("menu.description"),
      field: "description",
      hidden: true,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 懒加载数据，点击展开时触发，初次初始化数据通过 :data="state.initRows"
const load = async (
  row: MenuItemTreeNode,
  treeNode: any,
  resolve: (date: MenuItemTreeNode[]) => void
) => {
  let childs = await apiMenu.loadChilds(row.menuItemId);
  // console.log("load", row, treeNode, resolve);
  childs.forEach((m: any) => {
    m.hasChildren = m.hasChildren == 1 ? true : false;
    // 随机主键可以避免缓存，可以正常显示重复展开操作 >
    m.randomKey = utils.getUUID();
  });
  let nodes = Array<MenuItemTreeNode>();
  Object.assign(nodes, childs);
  resolve(nodes);
};

// 删除操作事件
const handleDelete = (row: any) => {
  // 从表格每行右侧链接点击触发的情况
  ElMessageBox.confirm(
    t("menu.confirmItemDelete", { menuItemName: row.menuItemName }),
    {
      confirmButtonText: t("common.okButton"),
      cancelButtonText: t("common.cancelButton"),
    }
  )
    .then(() => {
      apiMenu
        .deleteMenuItem(row.menuItemId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            utils.infoNotification(
              t("menu.itemDeleted", { menuItemName: row.menuItemName })
            );
          }
        })
        .catch((err: any) => {
          utils.errorNotification(t("common.submitException"), err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show(formSearch.menuId);
};
// 返回
const handleBack = () => {
  router.push({
    name: "/admin/menu/list",
  });
};
// 打开编辑页
const handleEdit = (row: any) => {
  editFormRef.value.show(formSearch.menuId, row);
};
// 新增、编辑页确定按钮操作成功回调事件
const onSubmitSuccess = (row: any) => {
  handleSearch();
};

onBeforeMount(() => {
  formSearch.menuId = String(router.currentRoute.value.params.menuId);

  apiMenu
    .getMenu(formSearch.menuId)
    .then((response: any) => {
      if (response.data.code == 200) {
        Object.assign(formSearch, response.data.data);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  initRootRows();
});

const initRootRows = () => {
  apiMenu
    .queryMenuItemChildrenListing("0")
    .then((response: any) => {
      let rows = response.data.data;
      rows.forEach((m: any) => {
        m.hasChildren = m.hasChildren == 1 ? true : false;
        // 随机主键可以避免缓存，可以正常显示重复展开操作 >
        m.randomKey = utils.getUUID();
      });
      state.initRows = rows;
      // console.log("initRootRows", rows);
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

// 刷新表格
const handleSearch = async () => {
  // dataGridRef.value.loadGridData();
  // 触发 load() 重新加载表格数据
  initRootRows();
};
</script>
